<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="98px">
        <el-form-item label="系统名称" prop="systemName">
          <!-- <el-input
            v-model="queryParams.systemName"
            placeholder="请输入系统编码"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          /> -->
          <el-select
            v-model="queryParams.systemName"
            placeholder="请选择系统名称"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
               v-for="dict in systemListDictData"
              :key="dict.sysNum"
              :label="dict.sysName"
              :value="dict.sysNum"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="系统名称" prop="systemNameCn">
          <el-input
            v-model="queryParams.systemNameCn"
            placeholder="请输入系统名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <el-form-item label="单点登陆类型" prop="ssoType">
          <el-select
            v-model="queryParams.ssoType"
            placeholder="请选择单点登陆类型"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="dict in ssoOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="单点登陆地址" prop="ssoUrl">
        <el-input
          v-model="queryParams.ssoUrl"
          placeholder="请输入单点登陆地址"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号字符" prop="usernameStr">
        <el-input
          v-model="queryParams.usernameStr"
          placeholder="请输入账号字符"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="密码字符" prop="passwordStr">
        <el-input
          v-model="queryParams.passwordStr"
          placeholder="请输入密码字符"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 240px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:ssoConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:ssoConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ssoConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:ssoConfig:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ssoConfigList" @selection-change="handleSelectionChange" :default-sort="{ prop: 'fieldSort', order: 'descending' }" @sort-change="tableSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" :sort-orders="['ascending', 'descending']" sortable="custom"/>
      <el-table-column label="系统名称" align="center" prop="systemName" :sort-orders="['ascending', 'descending']" sortable="custom">
        <template slot-scope="scope">
          <span>{{ systemSystemFormat(scope.row.systemName) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="系统名称" align="center" prop="systemNameCn" :sort-orders="['ascending', 'descending']" sortable="custom"/> -->
       <el-table-column label="系统类型" align="center" prop="ssoType" :sort-orders="['ascending', 'descending']" sortable="custom">
        <template slot-scope="scope">
          <span>{{ systemTypeFormat(scope.row.systemType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单点登陆类型" align="center" prop="ssoType" :sort-orders="['ascending', 'descending']" sortable="custom">
        <template slot-scope="scope">
          <span>{{ statusFormat(scope.row.ssoType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单点登陆地址" align="center" prop="ssoUrl" />
      <!-- <el-table-column label="账号字符" align="center" prop="usernameStr" :sort-orders="['ascending', 'descending']" sortable="custom"/>
      <el-table-column label="密码字符" align="center" prop="passwordStr" :sort-orders="['ascending', 'descending']" sortable="custom"/> -->
      <el-table-column label="状态" align="center" width="100" prop="status" :sort-orders="['ascending', 'descending']" sortable="custom">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="fieldSort" :sort-orders="['ascending', 'descending']" sortable="custom"/>
      <el-table-column label="图片地址" align="center" prop="functionType">
        <template slot-scope="scope">
         <img :src="scope.row.images" alt=""  width="30" height="30" >
        </template>
      </el-table-column>
      <!-- <el-table-column label="图片" align="center" prop="images" /> -->
      <el-table-column label="备注" align="center" prop="remark" :sort-orders="['ascending', 'descending']" sortable="custom"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ssoConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ssoConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户单点登录配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="98px">
        <el-form-item label="系统名称" prop="systemNameCn">
           <el-select v-model="systemName" placeholder="请选择系统名称">
            <el-option
              v-for="dict in systemListDictData"
              :key="dict.sysNum"
              :label="dict.sysName"
              :value="dict.sysNum"
            ></el-option>
          </el-select>
          <!-- <el-input v-model="form.systemNameCn" placeholder="请输入单点登陆名称" /> -->
        </el-form-item>
         <!-- <el-form-item label="系统编码" prop="systemNameCn" v-if="1!==1">
          <el-input v-model="form.systemName" placeholder="请输入单点登陆名称" />
        </el-form-item> -->
        <el-form-item label="单点登陆类型" prop="ssoType">
          <el-select v-model="form.ssoType" placeholder="请选择单点登陆类型">
            <el-option
              v-for="dict in ssoOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统类型" prop="systemType">
          <el-select v-model="form.systemType" placeholder="请选择系统类型">
            <el-option
              v-for="dict in systemTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统打开方式" prop="openWay">
          <el-select v-model="form.openWay" placeholder="请选择系统打开方式">
            <el-option
              v-for="dict in systemOpenOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单点登陆地址" prop="ssoUrl">
          <el-input type="textarea" autosize="true" v-model="form.ssoUrl" placeholder="请输入单点登陆地址" />
        </el-form-item>
        <el-form-item label="账号字符" prop="usernameStr" v-if="form.ssoType==3">
          <el-input v-model="form.usernameStr" placeholder="请输入账号字符" />
        </el-form-item>
        <el-form-item label="密码字符" prop="passwordStr" v-if="form.ssoType==3">
          <el-input v-model="form.passwordStr" placeholder="请输入密码字符" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="fieldSort">
          <el-input-number
            :precision="2"
            :step="0.1"
            v-model="form.fieldSort"
            placeholder="请输入排序"
          />
        </el-form-item>
        <el-form-item label="图片上传" prop="images">
          <el-upload
            ref="upload"
            :limit="1"
            :on-exceed="handleExceed"
            accept=".jpg, .png"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :multiple="false"
            :before-remove="beforeRemove"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button>
            <!-- <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              :loading="upload.isUploading"
              @click="submitUpload"
              >上传到服务器</el-button> -->
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
         <el-form-item label="图片地址" prop="images">
          <div v-if="form.images!=null&&form.images!=''">
            <el-link :underline="false" icon="el-icon-paperclip" style="text-align:left; float:left; overflow:hidden;white-space:nowrap;text-overflow:ellipsis; ">{{substr(form.images)}}</el-link>
            <el-link @click="downloadFiles()"> <i class="el-icon-download el-icon--right" ></i>下载</el-link>
            <el-link @click="deleteFile()"> <i class="el-icon-delete el-icon--right" ></i>删除</el-link>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSsoConfig,
  getSsoConfig,
  delSsoConfig,
  addSsoConfig,
  updateSsoConfig,
  exportSsoConfig,
  changeStatus
} from "@/api/system/ssoConfig";
import { getSystemListDictData } from "@/api/system/sysList";
import { getToken } from "@/utils/auth";
import { download, deleteFile} from "@/api/tool/tools";
export default {
  name: "SsoConfig",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户单点登录配置表格数据
      ssoConfigList: [],
      //单点登录类型
      ssoOptions:[],
      //状态类型
      statusOptions: [],
      //系统类型
      systemTypeOptions: [],
      //系统打开方式
      systemOpenOptions: [],
      //系统可用类型
      systemListDictData: [],
      systemName:"",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        systemName: null,
        systemNameCn: null,
        systemType:null,
        ssoType: null,
        ssoUrl: null,
        usernameStr: null,
        passwordStr: null,
        status: null,
        images: null,
        fieldSort: null,
      },
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }

    };

  },
  created() {
    this.getList();
    this.getDicts("sys_sso_type").then(response => {
      this.ssoOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
     this.getDicts("outside_system_type").then(response => {
      this.systemTypeOptions = response.data;
    });
    this.getDicts("outside_system_open").then(response => {
      this.systemOpenOptions = response.data;
    });
    this.getSystemListDictData();
  },
  watch: {
     systemName:{
      handler(newName, oldName) {
        console.log("新值： " + newName + ", 旧值：" + oldName)
        this.form.systemName = this.systemName;
      }
    },
  },
  methods: {
    /** 查询用户单点登录配置列表 */
    getList() {
      this.loading = true;
      listSsoConfig(this.queryParams).then(response => {
        this.ssoConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.systemName = null;
      this.systemNameCn = null;
      this.form = {
        id: null,
        systemName: null,
        systemNameCn: null,
        systemType: null,
        ssoType: null,
        ssoUrl: null,
        usernameStr: null,
        passwordStr: null,
        status: "0",
        images: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        fieldSort: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 系统状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.systemNameCn + '"吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户单点登录配置";
      this.upload.fileList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getSystemListDictData();
      const id = row.id || this.ids
      getSsoConfig(id).then(response => {
        this.form = response.data;
        this.systemName = response.data.systemName;
        this.open = true;
        this.title = "修改用户单点登录配置";
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSsoConfig(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSsoConfig(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除用户单点登录配置编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSsoConfig(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户单点登录配置数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSsoConfig(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    statusFormat(ssoType){
      let sso=this.ssoOptions;
        for (let i = 0; i < sso.length; i++) {
        if (sso[i].dictValue==ssoType){
          return sso[i].dictLabel;
        }
      }
    },
    systemTypeFormat(systemType){
      let system=this.systemTypeOptions;
        for (let i = 0; i < system.length; i++) {
        if (system[i].dictValue==systemType){
          return system[i].dictLabel;
        }
      }
    },
    systemSystemFormat(systemType){
      let system=this.systemListDictData;
        for (let i = 0; i < system.length; i++) {
        if (system[i].sysNum==systemType){
          return system[i].sysName;
        }
      }
    },
  // 文件提交处理
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.images = response.url;
      this.msgSuccess(response.msg);
      fileList = [];
    },
    // 重置表单操作
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
      }
      console.log(this.$refs["upload"])
      if (this.$refs["upload"] !== undefined) {
        this.$refs.upload.clearFiles();
      }
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
        console.log(file, fileList);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
        console.log(file);
    },
    // 选择时事件提醒
    handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件,请删除后重新下载`);
    },
    // 移出前事件提示
    beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
    },
    tableSortChange(column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    },
    getSystemListDictData(){
      getSystemListDictData().then(response => {
      this.systemListDictData = response.data;
      });
    },
    substr(str){
      if(str){
      //  return  str.substr(str.lastIndexOf("/")+1);
      return  "图片"+str.substr(str.lastIndexOf("."));
      }
    },
    downloadFiles(){
     download(this.substr(this.form.images),this.form.images);
    },
     deleteFile(){
     this.form.images="";
    },
  }
};
</script>
